﻿using System;
using System.Web.Mvc;
using Framework.Domain;
using Shell.DomainDot;
using System.Web.Security;
using Framework.Poco;
using System.Linq;
using Framework.Mvc.ViewModels;

namespace Framework.Mvc.Controllers
{
    /// <summary>
    /// 经销商控制器
    /// </summary>
    public class AgencyController : Controller
    {
        private IDomainDotFactory factory;

        /// <summary>
        /// 构造器
        /// </summary>
        public AgencyController()
        {
            factory = DomainDotFactory.Factory;
        }

        /// <summary>
        /// 获得注册信息
        /// </summary>
        [HttpGet]
        public ActionResult Register()
        {
            var context = factory.Create<GlobalContext>();
            AgencyBaseViewModel model = new AgencyBaseViewModel();
            model.AvailableAgencyGroups = context.GetAllAgencyGroups();
            model.AvailableDistricts = context.GetAllDistricts();
            return View(model);
        }

        /// <summary>
        /// 提交注册信息
        /// </summary>
        [HttpPost]
        public ActionResult Register(AgencyBaseViewModel model)
        {
            var context = factory.Create<GlobalContext>();
            if (String.IsNullOrEmpty(model.Instance.Name))
            {
                this.ModelState.AddModelError("Instance.Name", "用户名不能为空!");
                return View(new AgencyBaseViewModel { AvailableAgencyGroups = context.GetAllAgencyGroups(), AvailableDistricts = context.GetAllDistricts() });
            }
            if (String.IsNullOrEmpty(model.Instance.Password))
            {
                this.ModelState.AddModelError("Instance.Password", "密码不能为空!");
                return View(new AgencyBaseViewModel { AvailableAgencyGroups = context.GetAllAgencyGroups(), AvailableDistricts = context.GetAllDistricts() });
            }
            if (String.IsNullOrEmpty(model.Contact.Name))
            {
                this.ModelState.AddModelError("Contact.Name", "联系人姓名不能为空!");
                return View(new AgencyBaseViewModel { AvailableAgencyGroups = context.GetAllAgencyGroups(), AvailableDistricts = context.GetAllDistricts() });
            }
            if (String.IsNullOrEmpty(model.Contact.Phone))
            {
                this.ModelState.AddModelError("Contact.Phone", "联系电话不能为空!");
                return View(new AgencyBaseViewModel { AvailableAgencyGroups = context.GetAllAgencyGroups(), AvailableDistricts = context.GetAllDistricts() });
            }
            if (String.IsNullOrEmpty(model.Instance.DisplayName))
            {
                this.ModelState.AddModelError("Instance.DisplayName", "公司名称不能为空!");
                return View(new AgencyBaseViewModel { AvailableAgencyGroups = context.GetAllAgencyGroups(), AvailableDistricts = context.GetAllDistricts() });
            }
            if (String.IsNullOrEmpty(model.Instance.Address))
            {
                this.ModelState.AddModelError("Instance.Address", "公司详细地址不能为空!");
                return View(new AgencyBaseViewModel { AvailableAgencyGroups = context.GetAllAgencyGroups(), AvailableDistricts = context.GetAllDistricts() });
            }
            if (context.HasSameAgency(model.Instance.Name))
            {
                this.ModelState.AddModelError("Instance.Name", "用户已被注册");
                return View(new AgencyBaseViewModel { AvailableAgencyGroups = context.GetAllAgencyGroups(), AvailableDistricts = context.GetAllDistricts() });
            }
            if (context.HasSameDisplayName(model.Instance.DisplayName))
            {
                this.ModelState.AddModelError("Instance.DisplayName", "此公司名称已被注册");
                return View(new AgencyBaseViewModel { AvailableAgencyGroups = context.GetAllAgencyGroups(), AvailableDistricts = context.GetAllDistricts() });
            }
            context.AgencyRegirter(model.Instance, model.Contact, model.DistrictIdentity, model.AgencyGroupIdentity);
            return this.RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// 获得登陆时信息
        /// </summary>
        [HttpGet]
        public ActionResult LogOn()
        {
            return View();
        }

        /// <summary>
        /// 提交登陆信息
        /// </summary>
        [HttpPost]
        public ActionResult LogOn(LogOnViewModel model)
        {
            if (String.IsNullOrWhiteSpace(model.Name))
            {
                this.ModelState.AddModelError("Name", "用户名不能为空!");
            }
            else if (String.IsNullOrWhiteSpace(model.Password))
            {
                this.ModelState.AddModelError("Password", "密码不能为空!");
            }
            else if (String.IsNullOrWhiteSpace(model.VerfityCode))
            {
                this.ModelState.AddModelError("VerifyCode", "验证码不能为空!");
            }
            else
            {
                var verifyCode = Session["LogOnVerifyCode"].ToString();
                if (!String.IsNullOrEmpty(verifyCode) && verifyCode.Equals(model.VerfityCode, StringComparison.CurrentCultureIgnoreCase))
                {
                    var context = factory.Create<GlobalContext>();
                    var agency = context.FindNameAgency(model.Name);
                    if (agency != null && agency.IsVerification)
                    {
                        var hashedPassword = EncryptionHelper.Md5Hash(model.Password);
                        if (hashedPassword.Equals(agency.Password, StringComparison.CurrentCulture))
                        {
                            FormsAuthentication.SetAuthCookie(agency.Name, false);
                            return this.RedirectToAction("Index");
                        }
                        else
                        {
                            this.ModelState.AddModelError("Name", "用户名或密码错误!");
                        }
                    }
                    if (agency != null && !agency.IsVerification)
                    {
                        return this.RedirectToAction("NotReviewed");
                    }
                    if (agency == null)
                    {
                        this.ModelState.AddModelError("Name", "用户名或密码错误!");
                    }
                }
                else
                {
                    this.ModelState.AddModelError("VerfityCode", "验证码错误");
                }
            }
            model.Password = String.Empty;
            model.VerfityCode = String.Empty;
            return View(model);
        }

        /// <summary>
        /// 经销商管理首页
        /// </summary>
        [HttpGet]
        public ActionResult Index(Agency currentAgency)
        {
            if (currentAgency != null)
            {
                var context = factory.Create<GlobalContext>();
                Agency instance = context.FindIdentityAgency(currentAgency.Id);
                if (instance != null)
                {
                    var model = new AgencyIndexViewModel();
                    var agencyContext = factory.Create<AgencyContext>(currentAgency.Id);
                    model.Instance = context.FindIdentityAgency(currentAgency.Id);
                    var all = agencyContext.GetAllContact();
                    model.Contact = all.SingleOrDefault(c => c.IsDefault);
                    model.District = agencyContext.GetDistrict();
                    model.AgencyGroup = agencyContext.GetAgencyGroup();
                    model.AvailableAgencyGroups = context.GetAllAgencyGroups();
                    model.AvailableDistricts = context.GetAllDistricts();
                    return View(model);
                }
            }
            return this.RedirectToAction("LogOn");
        }

        /// <summary>
        /// 经销商管理首页
        /// </summary>
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Index(Agency currentAgency, AgencyIndexViewModel model)
        {
            if (currentAgency != null)
            {
                var globalContext = factory.Create<GlobalContext>();
                var agencyContext = factory.Create<AgencyContext>(model.Instance.Id);
                agencyContext.EditContact(model.Contact);
                globalContext.EditAgency(model.Instance, model.Contact);
                var script = String.Format("<script>alert('修改成功!');location.href='{0}'</script>", Url.Action("Index"));
                return Content(script);
            }
            return this.RedirectToAction("LogOn");
        }

        /// <summary>
        /// 地区修改
        /// </summary>
        [HttpGet]
        public ActionResult DistrictBindEdit(Agency currentAgency)
        {
            if (currentAgency != null)
            {
                var context = factory.Create<GlobalContext>();
                var agencyContext = factory.Create<AgencyContext>(currentAgency.Id);
                var model = new AgencyDistrictBindEditViewModel();
                model.Instance = currentAgency;
                model.District = agencyContext.GetDistrict();
                model.AvailableDistricts = context.GetAllDistricts();
                return View(model);
            }
            return this.RedirectToAction("LogOn");
        }

        /// <summary>
        /// 地区修改
        /// </summary>
        [HttpPost]
        public ActionResult DistrictBindEdit(Agency currentAgency, AgencyDistrictBindEditViewModel model)
        {
            if (currentAgency != null)
            {
                var agencyContext = factory.Create<AgencyContext>(currentAgency.Id);
                var globalContext = factory.Create<GlobalContext>();
                model.AvailableDistricts = globalContext.GetAllDistricts();
                if (agencyContext.GetDistrict().Id != model.SelectedDistrictIdentity && model.SelectedDistrictIdentity.HasValue)
                {
                    agencyContext.ReleaseDistrict();
                    agencyContext.BindDistrict(model.SelectedDistrictIdentity.Value);
                    model.District = agencyContext.GetDistrict();
                    return View(model);
                }
                return View(model);
            }
            return this.RedirectToAction("LogOn");
        }

        /// <summary>
        /// 行业类别修改
        /// </summary>
        [HttpGet]
        public ActionResult GroupBindEdit(Agency currentAgency)
        {
            if (currentAgency != null)
            {
                var context = factory.Create<GlobalContext>();
                var agencyContext = factory.Create<AgencyContext>(currentAgency.Id);
                var model = new AgencyGroupBindEditViewModel();
                model.Instance = currentAgency;
                model.AgencyGroup = agencyContext.GetAgencyGroup();
                model.AvailableAgencyGroups = context.GetAllAgencyGroups();
                return View(model);
            }
            return this.RedirectToAction("LogOn");
        }

        /// <summary>
        /// 行业类别修改
        /// </summary>
        [HttpPost]
        public ActionResult GroupBindEdit(Agency currentAgency, AgencyGroupBindEditViewModel model)
        {
            if (currentAgency != null)
            {
                var agencyContext = factory.Create<AgencyContext>(currentAgency.Id);
                var globalContext = factory.Create<GlobalContext>();
                model.AvailableAgencyGroups = globalContext.GetAllAgencyGroups();
                if (agencyContext.GetDistrict().Id != model.SelectedAgencyGroupIdentity && model.SelectedAgencyGroupIdentity.HasValue)
                {
                    agencyContext.ReleaseAgencyGroup();
                    agencyContext.BindAgencyGroup(model.SelectedAgencyGroupIdentity.Value);
                    model.AgencyGroup = agencyContext.GetAgencyGroup();
                    return View(model);
                }
                return View(model);
            }
            return this.RedirectToAction("LogOn");
        }

        /// <summary>
        /// 经销商未审核通过页面
        /// </summary>
        public ActionResult NotReviewed(AgencyNotReviewedViewModel model)
        {
            return View();
        }

        /// <summary>
        /// 经销商地图信息标记
        /// </summary>
        [HttpGet]
        public ActionResult SetMapMark(Agency currentAgency)
        {
            if (currentAgency != null)
            {
                return View(currentAgency);
            }
            return this.RedirectToAction("LogOn", "Agency");
        }

        /// <summary>
        /// 提交经销商地图信息
        /// </summary>
        [HttpPost]
        public ActionResult SetMapMark(Agency currentAgency, string mapMark)
        {
            if (currentAgency != null)
            {
                var context = this.factory.Create<AgencyMarkContext>();
                context.SetAgencyMark(currentAgency.Id, mapMark);
                return View(currentAgency);
            }
            return RedirectToAction("LogOn", "Agency");
        }

        /// <summary>
        /// 经销商密码修改
        /// </summary>
        [HttpGet]
        public ActionResult ChangePassword(Agency currentAgency)
        {
            if (currentAgency != null)
            {
                var context = factory.Create<GlobalContext>();
                var original = context.FindIdentityAgency(currentAgency.Id);
                if (original != null)
                {
                    var agencyChangePasswordViewModel = new ChangePasswordViewModel();
                    agencyChangePasswordViewModel.Instance = currentAgency;
                    return View(agencyChangePasswordViewModel);
                }
                else
                {
                    this.ModelState.AddModelError("Name", "无法找到指定的用户");
                }
            }
            else
            {
                this.ModelState.AddModelError("Name", "无法找到指定的用户");
            }
            return View();
        }

        /// <summary>
        /// 经销商密码修改
        /// </summary>
        [HttpPost]
        public ActionResult ChangePassword(Agency currentAgency, ChangePasswordViewModel model)
        {
            if (currentAgency != null && model.NewPassword == model.RepeatPassword)
            {
                var hashedOldPassword = EncryptionHelper.Md5Hash(model.OldPassword);
                var hashedNewPassword = EncryptionHelper.Md5Hash(model.NewPassword);
                if (String.Compare(currentAgency.Password, hashedOldPassword, false) == 0)
                {
                    var context = factory.Create<GlobalContext>();
                    context.ChangePassword(currentAgency, hashedNewPassword);
                    var script = String.Format("<script>alert('修改成功!');location.href='{0}'</script>", Url.Action("ChangePassword"));
                    return Content(script);
                }
                else
                {
                    this.ModelState.AddModelError("currentAgency.Password", "密码不正确!");
                    return View(currentAgency);
                }
            }
            else
            {
                this.ModelState.AddModelError("Name", "无法找到指定的用户");
            }
            return View();
        }

        /// <summary>
        /// 退出登陆
        /// </summary>
        public ActionResult Logoff()
        {
            FormsAuthentication.SignOut();
            return this.RedirectToAction("LogOn", "Agency");
        }
    }
}